<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Category extends MX_Controller
{
	protected $_templates;
	
	function __construct() 
	{
		parent::__construct();
		$this->pre_message = "";         
		/*$this->permit_library->check_permit();
		$this->session->set_userdata(array('Url'=>uri_string()));*/
		//load language
		//$this->load->helper('search') ;
		$this->lang->load('category');
		//$this->load->library('string_library');
		$this->load->model('category_model','category');
	}   
	
	function index($start=0)
	{
		/*Begin search*/
		$type = $this->input->post('type');
		$data['search_bar']= searchBar(array(),array('catname_vn'=>'Category Name'),'category/index/');
		if($type=='ajax')
		{
			$arr_search['key_search'] = $this->input->post('key_search');
			$arr_search['field_search'] = $this->input->post('field_search');
			$this->session->set_userdata('key_search',$arr_search['key_search']);
			$this->session->set_userdata('field_search',$arr_search['field_search']);
		}
		else
		{
			$arr_search['key_search']=$this->session->userdata('key_search');
			$arr_search['field_search']=$this->session->userdata('field_search');
		}
		/*End  search*/
		
		$data['start'] = $start ;
		
		$data['title'] = 'Category';
		$data['add'] = 'category/add';
		$config['base_url'] = base_url().'category/index/';  
		$data['num'] = $this->category->get_num_data($arr_search); 
		$config['total_rows'] =  $data['num'];
		$config['per_page'] = 30;
		$config['uri_segment'] = 3;   
		$this->pagination->initialize($config); 
		  
		$data['list'] =   $this->category->get_all_data($config['per_page'],$start,$arr_search);
		$data['pagination']    = $this->pagination->create_links();            
	    
		$data['page'] = 'index' ;
		$type = $this->input->post('type');
        if($type=="ajax")
            $this->load->view($data['page'], $data);
		else
			$this->load->view('layout/skin', $data);
		
		$this->createCategory();
		$this->createHtmlCategory();
	}
	
	function add()
	{                       
		$data['title'] = "Thêm Video Cactegory";
		$data['category_option'] = $this->category->optionCategoryLevel();
		
		if(isset($_POST['bt_submit']))
		{
			$this->form_validation->set_rules('catname_vn',lang('dsq_category_name'),'trim|required');
			if($this->form_validation->run() == FALSE){
				$this->pre_message = validation_errors();
			}else{
				$data = $this->_build_data();
				if($this->category->save($data)){
					$this->session->set_flashdata('message','Lưu thành công');
					redirect('category/index');
				}else{
					$this->pre_message = 'Lưu không thành công';
					redirect('category/add');
				}
			}
		}
		$data['message'] = $this->pre_message;
		$this->_templates['page'] = 'category/add';
		$this->site->load($this->_templates['page'],$data);
	}
	
	function edit($id)
	{                         
		$data['title'] = lang('title_edit');
		$data['rs'] = $this->category->get_detail($id);
		$data['category_option'] = $this->category->optionCategoryLevel(); //trit($data['category_option']);
		if(isset($_POST['bt_submit']))
		{
			$this->form_validation->set_rules('catname_vn',lang('dsq_category_name'),'trim|required');
			if($this->form_validation->run() == FALSE){
				$this->pre_message = validation_errors();
			}else{
				$req = $this->_build_data();
				if(!empty($req['lb_image']) && ($req['lb_image']!=$data['rs']->lb_image)) $this->delimg($data['rs']->lb_image);
				if($this->category->save($req,$id)){
					$this->session->set_flashdata('message','Lưu thành công');
					redirect('category/index');
				}else{
					$this->pre_message = 'Lưu không thành công';
					redirect('category/edit');
				}
			}
		}
		$data['message'] = $this->pre_message;
		$this->_templates['page'] = 'category/edit';
		$this->site->load($this->_templates['page'],$data);
	}
	
	function del($id=0,$page=0)
	{
		$rs = $this->category->get_detail($id);
		$this->delimg($rs->lb_image);
		if($this->category->deleted($id))
			$this->session->set_flashdata('message','Đã xóa thành công');
		else $this->session->set_flashdata('message','Xóa không thành công');
			redirect('news_category/index/'.$page);
	}
	
	private function delimg($filename='')
	{
		if(!empty($filename) && file_exists('../uploads/category/'.$filename)) @unlink('../uploads/category/'.$filename);
	}
	
	function dels()
	{
		if(!empty($_POST['ar_id']))
		{
			$page = (int)$this->input->post('page');
			$ar_id = $this->input->post('ar_id');
		
			if(!empty($_POST['btn_submit']))
			{
				for($i = 0; $i < sizeof($ar_id); $i ++) 
				{
					if ($ar_id[$i])
					{
						//Xoa cac anh cu va data
						$rs = $this->category->get_detail($ar_id[$i]);
						$this->delimg($rs->lb_image);
						if($this->category->deleted($ar_id[$i]))
							$this->session->set_flashdata('message','Đã xóa thành công');
						else $this->session->set_flashdata('message','Xóa không thành công');
					}
				}
			}
		}
		redirect('news_category/index/'.$page);
	}
	
	function _build_data($flag=1)
	{
		$req["catsub"] = $this->input->post("catsub",0);
		$req["catname_vn"] = $this->input->post("catname_vn");
		$req["catname_en"] = $this->input->post("catname_en");
		$req["nb_level"] = $req["catsub"]? 1 : 0;
		$req["nb_order"] = $this->input->post("nb_order");
		$req["bl_active"] = (int) $this->input->post("bl_active");
		$req["dt_create"] = date('Y-m-d');
		
		//upload hinh anh
		$img = $this->input->post("lb_image");
		$img_name = end(explode('/', $img)) ;
		if($img)
		{
			if(file_exists('../uploads/category/'.$img_name))
			{
				@unlink('../uploads/category/'.$img_name);
			}
			fn_resize_image('../uploads/'.$img,'../uploads/category/'.$img_name, 120, 120); 
			@unlink('../uploads/temp/'.$img_name);
			$req["lb_image"] = $img_name;
		}
		return $req;
	}
	
	//============= create file catebory===============
	function createCategory()
	{
		$arrCat=$this->category->getCategory(0);
		$countCat=count($arrCat);
		$dir=DIR_DATA.'/config_category.php';
		$str = "<?php  \n/**\n* Cache file for news.dev \n* Date: ".date('d/m/y H:i:s').".\n**/\n";
		if($countCat>0){
			foreach($arrCat as $cat){
				$str.="\$config[\"$cat->catid\"] = \"$cat->catname_vn\";\n";
				$arrCat2=$this->category->getCategory($cat->catid);
				if(count($arrCat2)>0){
						foreach($arrCat2 as $cat2){
							$str.="\$config[\"$cat2->catid\"] = \"$cat2->catname_vn\";\n";
						}
				}
			}
		}
		$str .= "\n";
		$str .= "\n";
		$str .= "\n\n/* End of file menu*/\n/* Location: ./data/config_category.php */"; 
		if(file_put_contents($dir,$str))
			return true;
		else
			return false;
	}
	
	function createHtmlCategory()
	{
		$arrCat=$this->category->getCategory(0);
		$countCat=count($arrCat);
		
		$str_vn = "<?php  \n/**\n* Cache file for news.dev \n* Date: ".date('d/m/y H:i:s').".\n**/\n";
		$str_en = "<?php  \n/**\n* Cache file for news.dev \n* Date: ".date('d/m/y H:i:s').".\n**/\n";
		if($countCat>0)
		{
			 $str_vn .= "\$html='<ul>\n";
			 $str_en .= "\$html='<ul>\n";
			 $icon = DOMAIN.'/templates/images/index-pro.gif" width="4" height="4' ;
			 foreach($arrCat as $cat)
			 {
				$links_vn = DOMAIN.'/vn/sanpham/category/'.$cat->catid.'/'.kodau($cat->catname_vn).'.html';
			 	$links_en = DOMAIN.'/vn/sanpham/category/'.$cat->catid.'/'.kodau($cat->catname_vn).'.html';
				$str_vn.= '<li><a href="'.$links_vn.'"><img src="'.$icon.'">'.$cat->catname_vn.'</a></li>'."\n";
				$str_en.= '<li><a href="'.$links_vn.'"><img src="'.$icon.'">'.$cat->catname_en.'</a></li>'."\n";
			 }
			$str_vn.="\t</ul>\n';";
			$str_en.="\t</ul>\n';";
		}
		$str_vn .= "\n\n\n/* End of file menu*/\n/* Location: ./data/html_category_vn.php */"; 
		$str_en .= "\n\n\n/* End of file menu*/\n/* Location: ./data/dir_en.php */"; 
		
		$dir_vn = DIR_DATA.'/html_category_vn.php';
		$dir_en = DIR_DATA.'/html_category_en.php';
		
		write_file($dir_vn, $str_vn);
		write_file($dir_en, $str_en);
		return true;
	}
}
?>
